﻿/* -----------------------------------------------------------------------
 * <copyright file="AddNewAccountChild.xaml.cs" company="O-RID">
 *     Copyright (c)2010 O-RID Co.,Ltd.
 * </copyright>
 * <author>Zhang jun</author>
 * <summary>
 *          新增用户 子窗体
 *                      
 *          引用服务：WCFServers.WCFAccountsRefy
 *          服务功能：数据查询 
 *          
 *          引用服务：WCFLog4Ref.WCLog4Client
 *          服务功能：记录日志
 *        
 *        开始日期：09/17/2010
 *        作成日：  09/21/2010
 * </summary>
 * -----------------------------------------------------------------------
 */

namespace Orid.Management.Statistics.OperatorUnitMangement.CompetenceSetPaeg.AccountManagement
{
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Linq;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Media;
    using Orid.Management.Statistics.OperatorUnitMangement.WCFLog4Ref;
    using Orid.Management.Statistics.OperatorUnitMangement.WCFServers.WCFAccountsRef;
    using childWindow = Orid.Management.Statistics.OperatorUnitMangement.Common.Window;

    /// <summary>
    /// 
    /// </summary>
    public partial class AddNewAccountChild : ChildWindow
    {
        #region 全局变量
        /// <summary>
        /// 当前查询框的名字（日志用）
        /// </summary>
        private string ctrlName = " 新增用户子窗体 AddNewAccountChild ";

        /// <summary>
        /// 错误提示子窗口
        /// errorMessbox
        /// </summary>
        private childWindow.MessageBox errorMessbox;

       /// <summary>
        /// 服务定义
        /// accountsClient
        /// </summary>
        private WCFAccountsClient accountsClient;

        /// <summary>
        /// 日志服务定义
        /// WCFLog4Client
        /// </summary>
        private WCFLog4Client wcfLogClient;

        /// <summary>
        /// 记录最大的ID号
        /// </summary>
        private int lastID;
        /// <summary>
        /// 已有用户信息列表
        /// </summary>
        private List<AccountData> accountDateList;

        /// <summary>
        /// dataGrid数据源
        /// </summary>
        private List<AccountData> dataGridDateList;

        /// <summary>
        /// 记录当前操作的值
        /// </summary>
        private AccountData accountInfor;

        /// <summary>
        /// 要增加的记录内容
        /// </summary>
        ObservableCollection<AccountData> insertlist;

        /// <summary>
        /// 消息子窗口
        /// InformationMessbox
        /// </summary>
        private childWindow.MessageBox InformationMessbox;


        #endregion  全局变量

        /// <summary>
        /// Initializes a new instance of the class.
        /// </summary>
        public AddNewAccountChild()
        {
            InitializeComponent();
            
            Initialize();

            // 引用主题
            ((App)Application.Current).SetTheme(LayoutRoot);


            //页面载入
            this.Loaded += new RoutedEventHandler(AddNewAccountChild_Loaded);
            
            //查询已有用户信息
            accountsClient.AccountInforListCompleted += 
                            new EventHandler<AccountInforListCompletedEventArgs>(accountsClient_AccountInforListCompleted);
            //ComboBox选择操作
            this.cbSelectTpye.SelectionChanged += new SelectionChangedEventHandler(cbSelectTpye_SelectionChanged);
            //选择操作确定按钮
            this.btnSelectTpyeOK.Click += new RoutedEventHandler(btnSelectTpyeOK_Click);
            //DataGrid改变选择时
            this.dgNewAccount.SelectionChanged += new SelectionChangedEventHandler(dgNewAccount_SelectionChanged);
            //WCFAccount服务--增加新增记录(委托)
            accountsClient.InsertNewAccountCompleted += new EventHandler<InsertNewAccountCompletedEventArgs>(accountsClient_InsertNewAccountCompleted);
            //确定
            this.OKButton .Click +=new RoutedEventHandler(OKButton_Click);
            //取消
            this.CancelButton.Click +=new RoutedEventHandler(CancelButton_Click);
        }


        /// <summary>
        /// 变量初始化
        /// </summary>
        public void Initialize()
        {
            errorMessbox = new childWindow.MessageBox();
            accountsClient = new WCFAccountsClient();
            wcfLogClient = new WCFLog4Client();
            accountDateList = new List<AccountData>();
            dataGridDateList = new List<AccountData>();
            insertlist = new ObservableCollection<AccountData>();
            InformationMessbox=new childWindow.MessageBox();
            lastID = 0;
        }

        #region  页面载入 查询已有用户信息
        /// <summary>
        /// 页面载入
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The instance containing the event data.</param>
        void AddNewAccountChild_Loaded(object sender, RoutedEventArgs e)
        {
            try 
            {
                isEnableText(false);
                accountDateList.Clear();
                accountsClient.AccountInforListAsync();
            }
            catch (Exception ex) 
            {
                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr + ctrlName + ex.Message.ToString());

                Common.FunctionList.FunctionClass.ShowMessageBox(
                    this.errorMessbox,
                    1,
                    "提示",
                    ex.Message.ToString(),
                    Colors.Gray,
                    true,
                    Visibility.Visible,
                    Visibility.Collapsed);
                return;

            }
        }

        /// <summary>
        /// 查询已有用户信息
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The  instance containing the event data.</param>
        void accountsClient_AccountInforListCompleted(object sender, AccountInforListCompletedEventArgs e)
        {
            try
            {
                if (e.Error == null)
                {
                    if (e.Result.Count > 0)
                    {
                        //返回结果已排序
                        accountDateList= (from account in e.Result
                                          select account).ToList<AccountData>();

                        //如果dataGridDateList有内容，ID号的值是DataGrid中的最大号+1
                        if (this.dataGridDateList.Count > 0)
                        {
                            this.tbAccountID.Text = (dataGridDateList.Max(c => c.Id) + 1).ToString();
                            //两个LINQ是等效的
                            //this.tbAccountID.Text = (from maxid in this.dataGridDateList
                            //                         orderby maxid.Id descending
                            //                         select maxid.Id).Take<int>(1) + 1.ToString();
                        }
                        else
                        {
                            this.lastID = accountDateList[0].Id + 1;
                            this.tbAccountID.Text = this.lastID.ToString();
                        }
                    }
                    else
                    {
                        throw new Exception("没有可显示的数据！");
                    }
                }
                else 
                {
                    throw new Exception(e.Error.ToString());
                }

            }
            catch (Exception ex)
            {
                this.tbAccountID.Text = string.Empty;

                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr + ctrlName + ex.Message.ToString());

                Common.FunctionList.FunctionClass.ShowMessageBox(
                    this.errorMessbox,
                    1,
                    "提示",
                    ex.Message.ToString(),
                    Colors.Gray,
                    true,
                    Visibility.Visible,
                    Visibility.Collapsed);
                return;
            }
        }
        #endregion  页面载入 查询已有用户信息

        #region ComboBox选择操作 选择操作确定按钮
        /// <summary>
        /// ComboBox选择操作
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The instance containing the event data.</param>
        void cbSelectTpye_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (string.IsNullOrEmpty(this.tbAccountID.Text)) 
            {
                this.cbSelectTpye.SelectedIndex = -1;
                return;
            }
            accountInfor = null;
            accountInfor = new AccountData();
            switch (this.cbSelectTpye.SelectedIndex)
            {
                //添加
                case 0:
                    isEnableText(true);
                    break;
                //编辑
                case 1: 
                    isEnableText(true);
                    //记录要修改的记录号
                    accountInfor.OldAccountID = this.tbLoginID.Text.Trim();
                    break;
                //删除 
                case 2:
                    isEnableText(false);
                    if (string.IsNullOrEmpty(this.tbLoginID.Text.Trim())) 
                    {
                        return;
                    }
                    //记录要删除的记录号
                    accountInfor.OldAccountID = this.tbLoginID.Text.Trim();
                    break;
                //刷新
                case 3:
                    isEnableText(false);
                    break;
                default: break;
            }
           
        }
        /// <summary>
        /// 选择操作确定按钮
        /// 将已完成的结果添加到DATAGRID 中
        /// 刷新功能 
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <instance containing the event data.</param>
        void btnSelectTpyeOK_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                isEnableText(false);

                if (this.tbPassword.Password != this.tbPasswrod2.Password)
                {
                    throw new Exception("密码值不一致，请重新输入。");
                }
                switch (this.cbSelectTpye.SelectedIndex)
                {
                    //添加
                    case 0:
                        IsEmptyTextBox();
                        accountInfor.Id = Convert.ToInt32(this.tbAccountID.Text.Trim());
                        accountInfor.AccountID = this.tbLoginID.Text.Trim();
                        accountInfor.OpName = this.tbLoginName.Text.Trim();
                        accountInfor.PassWord = this.tbPasswrod2.Password.Trim();

                        //判断是否有重复值
                        if (isRecordCount(accountDateList, accountInfor) > 0 ||
                            isRecordCount(dataGridDateList, accountInfor) > 0)
                        {
                            throw new Exception("此用户已存在，请重新输入。");
                        }
                        dataGridDateList.Add(accountInfor);
                        // ID号自增
                        this.tbAccountID.Text = (++lastID).ToString();
                        break;
                    //编辑
                    case 1:
                        accountInfor.Id = Convert.ToInt32(this.tbAccountID.Text.ToString().Trim());
                        accountInfor.AccountID = this.tbLoginID.Text.ToString().Trim();
                        accountInfor.OpName = this.tbLoginName.Text.ToString().Trim();
                        accountInfor.PassWord = this.tbPasswrod2.Password.ToString().Trim();

                        //把要修改的记录先移除
                        for (int i = 0; i < dataGridDateList.Count; i++)
                        {
                            if (dataGridDateList[i].AccountID.ToUpper().Trim() == accountInfor.OldAccountID.ToUpper().Trim())
                            {
                                dataGridDateList.RemoveAt(i);
                            }
                        }

                        //判断是否有重复值
                        if (isRecordCount(accountDateList, accountInfor) > 0 ||
                            isRecordCount(dataGridDateList, accountInfor) > 0)
                        {
                            throw new Exception("此用户已存在，请重新输入。");
                        }

                         //再添加到LIST中
                        dataGridDateList.Add(accountInfor);
                        break;
                    //删除
                    case 2:
                        if (string.IsNullOrEmpty(accountInfor.OldAccountID)) 
                        {
                            return;
                        }
                        //把要修改的记录先移除
                        for (int i = 0; i < dataGridDateList.Count; i++)
                        {
                            if (dataGridDateList[i].AccountID.ToUpper().Trim() == accountInfor.OldAccountID.ToUpper().Trim())
                            {
                                dataGridDateList.RemoveAt(i);
                            }
                        }
                        ClearTextBox();
                        break;
                    //刷新
                    case 3:
                        accountsClient.AccountInforListAsync();
                        break;
                    default: return;
                }
                this.cbSelectTpye.SelectedIndex = -1;
                this.dgNewAccount.ItemsSource = null;
                this.dgNewAccount.ItemsSource = this.dataGridDateList;
            }
            catch (Exception ex) 
            {
                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr + ctrlName + ex.Message.ToString());
                this.cbSelectTpye.SelectedIndex = -1;
                Common.FunctionList.FunctionClass.ShowMessageBox(
                    this.errorMessbox,
                    1,
                    "提示",
                    ex.Message.ToString(),
                    Colors.Gray,
                    true,
                    Visibility.Visible,
                    Visibility.Collapsed);
                return;
            }
        }
        #endregion ComboBox选择操作 选择操作确定按钮

        #region DataGrid 行择
        /// <summary>
        /// DataGrid改变选择时
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The instance containing the event data.</param>
        void dgNewAccount_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                this.cbSelectTpye.SelectedIndex = -1;
                var selectData = e.AddedItems[0] as WCFServers.WCFAccountsRef.AccountData;

                if (selectData != null)
                {
                    this.tbAccountID.Text = selectData.Id.ToString().Trim();
                    this.tbLoginID.Text = selectData.AccountID.Trim();
                    this.tbLoginName.Text = selectData.OpName.Trim();
                    this.tbPassword.Password = selectData.PassWord.Trim();
                    this.tbPasswrod2.Password = selectData.PassWord.Trim();
                }
                else
                {
                    return;
                }
            }
            catch (Exception ex)
            {
                //索引超界
                return;
            }
        }
        #endregion DataGrid 行择

        #region 确定 按钮
        /// <summary>
        /// 确定 按钮
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The instance containing the event data.</param>
        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //把DataGrid里的值添加到数据库里
                if (this.dataGridDateList.Count <= 0)
                {
                    return;
                }

                //把LIST(dataGridDateList)变成ObservableCollection(insertlist)
                dataGridDateList.ForEach(x => insertlist.Add(x));
                accountsClient.InsertNewAccountAsync(insertlist);

                this.DialogResult = true;
            }
            catch
            {
                insertlist.Clear();
                accountDateList.Clear();
                dataGridDateList.Clear();

                this.DialogResult = true;
                return;
            }
        }

        /// <summary>
        /// 增加新增记录(实现)
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The instance containing the event data.</param>
        void accountsClient_InsertNewAccountCompleted(object sender, InsertNewAccountCompletedEventArgs e)
        {
            try
            {
                if (e.Error == null) 
                {
                    if (e.Result.Length > 0) 
                    {
                        this.wcfLogClient.InfoAsync(((App)Application.Current).LogStr + ctrlName
                                                        + " 增加" + dataGridDateList.Count.ToString() + "个新用户 " + e.Result.ToString());
                        throw new Exception(" 增加" + dataGridDateList.Count.ToString() + "个新用户 " + e.Result.ToString());
                    }
                }
                else 
                {
                    this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr + ctrlName 
                                                    + " InsertNewAccount方法 "+e.Error.Message);
                    throw new Exception(" InsertNewAccount方法 " + e.Error.Message);
                }
            }
            catch (Exception ex)
            {
                this.cbSelectTpye.SelectedIndex = -1;
                
                insertlist.Clear();
                accountDateList.Clear();
                dataGridDateList.Clear();

                Common.FunctionList.FunctionClass.ShowMessageBox(
                    this.errorMessbox,
                    1,
                    "提示",
                    ex.Message.ToString(),
                    Colors.Gray,
                    true,
                    Visibility.Visible,
                    Visibility.Collapsed);
                return;

            }
        }
        #endregion 确定 按钮

        #region 取消 按钮
        /// <summary>
        /// 取消 按钮
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The instance containing the event data.</param>
        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.dgNewAccount.ItemsSource = null;
            this.dataGridDateList.Clear();
            this.accountDateList.Clear();

            this.wcfLogClient.InfoAsync(((App)Application.Current).LogStr + ctrlName
                                + " 取消 增加新用户 ");

            this.DialogResult = false;
        }
        #endregion 取消 按钮

        #region TextBox是否可用
        /// <summary>
        /// TextBox是否可用
        /// </summary>
        /// <param name="isEnable">true:可用  false:不可用</param>
        private void isEnableText(bool isEnable) 
        {
            this.tbAccountID.IsEnabled = isEnable;
            this.tbLoginID.IsEnabled = isEnable;
            this.tbLoginName.IsEnabled = isEnable;
            this.tbPassword.IsEnabled = isEnable;
            this.tbPasswrod2.IsEnabled = isEnable;

        }
        #endregion TextBox是否可用

        #region 清空文本框
        /// <summary>
        /// 清空文本框
        /// </summary>
        private void ClearTextBox()
        {
            this.tbAccountID.Text = string.Empty;
            this.tbLoginID.Text = string.Empty;
            this.tbLoginName.Text = string.Empty;
            this.tbPassword.Password = string.Empty;
            this.tbPasswrod2.Password = string.Empty;

        }
        #endregion 清空文本框

        #region 判断指定的StackPanel里的TextBox是否为空值
        /// <summary>
        /// 判断TextBox是否为空值
        /// </summary>
        private void IsEmptyTextBox()
        {
            foreach (UIElement uiObject in spInputPanel.Children)
            {
                StackPanel uiStackPanel = uiObject as StackPanel;
                //如果是StackPanel
                if (uiStackPanel != null)
                {
                    foreach (UIElement ui in uiStackPanel.Children)
                    {
                        TextBox tb = ui as TextBox;
                        PasswordBox pb = ui as PasswordBox;
                        if (tb != null)
                        {
                            if (string.IsNullOrEmpty(tb.Text))
                            {
                                throw new Exception("输入值不能为空！");
                            }
                        }

                        if (pb != null)
                        {
                            if (string.IsNullOrEmpty(pb.Password))
                            {
                                throw new Exception("密码值不能为空！");
                            }
                        }
                    }
                }
            }
        }
        #endregion 判断指定的STACKPANEL里的TEXTBOX是否为空值

        #region 判断是否有重复值
        /// <summary>
        /// 判断是否有重复值
        /// </summary>
        /// <param name="accountData">The accountDataList Source/datagrid Source（数据源）</param>
        /// <param name="classAccount">The class account.(条件)</param>
        /// <returns></returns>
        int isRecordCount(List<AccountData> accountData,AccountData classAccount) 
        {
            int Num = (from acclist in accountData
                       where (acclist.Id == classAccount.Id
                                || acclist.AccountID.ToUpper() == classAccount.AccountID.ToUpper())
                       select acclist.AccountID).Count<string>();

             return Num;
        }
        #endregion 判断是否有重复值
    }
}

